package com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.impl.returnorder;

import com.alibaba.citrus.cr.mn.order.center.facade.adapter.ItemQueryAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.ItemSpecQueryAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemGroupAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemSearchAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemUnitAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.*;
import com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.OrderBizAssemble;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crplatformenhance.api.scitemquery.service.ScItemQueryService;
import com.epoch.app.crplatformenhance.model.dto.ScItemSDO;
import com.epoch.app.mnordercenter.model.dto.ReturnOrderBizCreateRequest;
import com.epoch.app.mnordercenter.model.dto.SalesOrderAtomCreateLineRequest;
import com.epoch.app.mnordercenter.service.MnOrderCenterService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @ClassName OrderBizAssembleOfMember
 * @description: TODO
 * @date 2023/05/17 09:49
 * @version: 1.0
 */
@Service
@Order(2)
public class ReturnOrderBizAssembleOfItemCenter implements OrderBizAssemble<ReturnOrderBizCreateRequest> {

    private static final Log log = Log.getLogger(ReturnOrderBizAssembleOfItemCenter.class);

    @Resource
    private ScItemQueryService scItemQueryService;

    @Resource
    private MnOrderCenterService mnOrderCenterService;

    @Resource
    private ItemQueryAdapter itemQueryAdapter;

    @Resource
    private ItemSpecQueryAdapter itemSpecQueryAdapter;

    @Override
    public Map<String, Object> query(ReturnOrderBizCreateRequest returnOrderBizCreateRequest) {
       return query(Lists.newArrayList());
    }

    @Override
    public Map<String, Object> query(List<ReturnOrderBizCreateRequest> returnOrderBizCreateRequests) {
        try {
            // 产品组
            Map<String, ItemGroupAbilityDTO> scItemGroupListQueryMap = queryScItemGroupMap(returnOrderBizCreateRequests);
            // 销售单位、库存单位
            Map<String, ItemUnitAbilityDTO> scItemUnitListQueryMap = queryScItemUnitMap(returnOrderBizCreateRequests);
            // 物料
            Map<String, ItemSearchAbilityDTO> scItemInfoMap = queryScItemMap(returnOrderBizCreateRequests);
            // 箱柜关系
            Map<String, SpecConvertCoefficientDTO> productConvertRelationMap = productConvertRelation(returnOrderBizCreateRequests);

            Map<String, Object> result = Maps.newHashMap();
            result.put(SC_ITEM_GROUP, scItemGroupListQueryMap);
            result.put(SC_ITEM_UNIT, scItemUnitListQueryMap);
            result.put(SC_ITEM_INFO, scItemInfoMap);
            result.put(SC_ITEM_CONVERT_RELATION, productConvertRelationMap);
            log.info("销售订单商业能力商品中心数据组装结果 result={}", JSONObject.toJSONString(result));
            return result;
        } catch (Exception e) {
            log.error("销售订单商业能力商品中心数据组装失败", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result<String> assemble(Map<String, Object> queryResponseMap, ReturnOrderBizCreateRequest createRequest) {
        // 产品组
        Map<String, ItemGroupAbilityDTO> scItemGroupMap = getBizInfoMap(queryResponseMap, SC_ITEM_GROUP, ItemGroupAbilityDTO.class);
        // 销售单位、库存单位
        Map<String, ItemUnitAbilityDTO> scItemUnitMap =  getBizInfoMap(queryResponseMap, SC_ITEM_UNIT, ItemUnitAbilityDTO.class);
        // 物料
        Map<String, ItemSearchAbilityDTO> scItemInfoMap = getBizInfoMap(queryResponseMap, SC_ITEM_INFO, ItemSearchAbilityDTO.class);
        // 箱柜关系
        Map<String, SpecConvertCoefficientDTO> productConvertRelationMap = getBizInfoMap(queryResponseMap, SC_ITEM_CONVERT_RELATION, SpecConvertCoefficientDTO.class);

        // 产品组
        ItemGroupAbilityDTO scItemGroup = scItemGroupMap.get(createRequest.getProductGroupCode());
        if (Objects.isNull(scItemGroup)) {
            return Result.fail(createRequest.getSourceOrderNo(),"OC-01-001-01-16-036", "产品组编码/名称不存在");
        }
        createRequest.setProductGroupName(scItemGroup.getProductGroupName());

        for (SalesOrderAtomCreateLineRequest orderDetail : createRequest.getOrderDetails()) {
            // 销售单位
            ItemUnitAbilityDTO scItemUnit = scItemUnitMap.get(orderDetail.getSalesUnitCode());
            if (Objects.isNull(scItemUnit)) {
                return Result.fail(createRequest.getSourceOrderNo(),"OC-01-001-01-16-052", "销售单位不存在");
            }
            orderDetail.setSalesUnitName(scItemUnit.getUnitName());
            // 物料信息
            ItemSearchAbilityDTO scItem = scItemInfoMap.get(orderDetail.getProductCode());
            if (Objects.isNull(scItem)) {
                return Result.fail(createRequest.getSourceOrderNo(),"OC-01-001-01-16-012", "物料编码不存在");
            }
            orderDetail.setInnerProductCode(scItem.getProductCode());
            orderDetail.setInnerProductName(scItem.getTitle());
            orderDetail.setProductBarCode(scItem.getBarCode());
            orderDetail.setProductName(scItem.getTitle());
            orderDetail.setStockUnitName(scItem.getUnit());
            orderDetail.setStockUnitCode(scItem.getUnitCode());

            SpecConvertCoefficientDTO productConvert = productConvertRelationMap.get(scItem.getScItemId());
            if (Objects.isNull(productConvert) || CollectionUtils.isEmpty(productConvert.getConvertCoefficientList())) {
                return Result.fail(createRequest.getSourceOrderNo(),"OC-01-001-01-16-039", "单位转换关系不存在");
            }
            // 库存转换数量计算
            calculateInventoryConvertNum(orderDetail, scItemUnit, productConvert);
        }
        return Result.success(null);
    }

    private void calculateInventoryConvertNum(SalesOrderAtomCreateLineRequest orderDetail, ItemUnitAbilityDTO scItemSalesUnit, SpecConvertCoefficientDTO productConvert) {

        List<SpecConvertCoefficientDetailDTO> convertRelations = productConvert.getConvertCoefficientList();
        for (SpecConvertCoefficientDetailDTO convertRelation : convertRelations) {
            if (StringUtils.equals(convertRelation.getUnitCode(), scItemSalesUnit.getUnitCode())) {

                Integer convertCoefficient = convertRelation.getConvertCoefficient();

                orderDetail.setUnitConversionRelationship(String.valueOf(convertCoefficient));

                if(StringUtils.isNotBlank(orderDetail.getProductQuantity()) && Objects.nonNull(convertCoefficient)) {

                    BigDecimal stockConversionNum = new BigDecimal(orderDetail.getProductQuantity())
                            .divide(new BigDecimal(String.valueOf(convertCoefficient)), 3, RoundingMode.HALF_UP);

                    orderDetail.setStockConversionNum(stockConversionNum.toPlainString());
                }
            }
        }
    }

    private Map<String, ItemGroupAbilityDTO> queryScItemGroupMap(List<ReturnOrderBizCreateRequest> returnOrderBizCreateRequests) {
        // 查询所有货品组数据
        ItemGroupAbilityRequest listRequest = new ItemGroupAbilityRequest();
        listRequest.setLimit(999);
        List<ItemGroupAbilityDTO> listResponse = itemQueryAdapter.queryScItemGroup(listRequest);
        return listResponse.stream().collect(Collectors.toMap(ItemGroupAbilityDTO::getProductGroupCode, p -> p, (v1, v2) -> v1));
    }

    private Map<String, ItemSearchAbilityDTO> queryScItemMap(List<ReturnOrderBizCreateRequest> returnOrderBizCreateRequests) {
        List<String> scItemOutIds = Lists.newArrayList();
        for (ReturnOrderBizCreateRequest returnOrderBizCreateRequest : returnOrderBizCreateRequests) {
            for (SalesOrderAtomCreateLineRequest orderDetail : returnOrderBizCreateRequest.getOrderDetails()) {
                scItemOutIds.add(orderDetail.getProductCode());
            }
        }
        ItemSearchAbilityRequest listRequest = new ItemSearchAbilityRequest();
        listRequest.setProductCodes(scItemOutIds);
        listRequest.setStatusList(Collections.singletonList(1));
        List<ItemSearchAbilityDTO> scItemInfoList = itemQueryAdapter.queryItem(listRequest);

        return Optional.ofNullable(scItemInfoList)
                .orElse(Lists.newArrayList())
                .stream().collect(Collectors.toMap(ItemSearchAbilityDTO::getOuterId, p -> p, (v1, v2) -> v1));
    }

    private List<ScItemSDO> parseScItemInfoList(Object listResponse) {
        JSONObject listResponseMap = JSONObject.parseObject((String) listResponse);
        JSONObject level1 = listResponseMap.getJSONObject("result");
        if (MapUtils.isEmpty(level1)) {
            return Lists.newArrayList();
        }
        JSONObject level2 = level1.getJSONObject("result");
        if (MapUtils.isEmpty(level2)) {
            return Lists.newArrayList();
        }
        JSONArray content = level2.getJSONArray("content");
        if (CollectionUtils.isEmpty(content)) {
            return Lists.newArrayList();
        }
        return JSONArray.parseArray(content.toJSONString(), ScItemSDO.class);
    }

    private Map<String, ItemUnitAbilityDTO> queryScItemUnitMap(List<ReturnOrderBizCreateRequest> returnOrderBizCreateRequests) {
        // 查询所有单位库数据
        ItemUnitAbilityRequest listRequest = new ItemUnitAbilityRequest();
        listRequest.setLimit(999);
        List<ItemUnitAbilityDTO> listResponse = itemQueryAdapter.queryScItemUnitMap(listRequest);
        return listResponse.stream().collect(Collectors.toMap(ItemUnitAbilityDTO::getUnitCode, p -> p, (v1, v2) -> v1));
    }

    private Map<String, SpecConvertCoefficientDTO> productConvertRelation(List<ReturnOrderBizCreateRequest> returnOrderBizCreateRequests) {

        List<String> materialCodeList = Lists.newArrayList();
        for (ReturnOrderBizCreateRequest returnOrderBizCreateRequest : returnOrderBizCreateRequests) {
            for (SalesOrderAtomCreateLineRequest orderDetail : returnOrderBizCreateRequest.getOrderDetails()) {
                if (StringUtils.isNotBlank(orderDetail.getProductCode())) {
                    materialCodeList.add(orderDetail.getProductCode());
                }
            }
        }

        if (CollectionUtils.isEmpty(materialCodeList)) {
            return Maps.newHashMap();
        }

        List<SpecConvertCoefficientDTO> listResult =
                itemSpecQueryAdapter.queryConvertCoefficientByMaterialCodeList(materialCodeList);

        if (CollectionUtils.isEmpty(listResult)) {
            return Maps.newHashMap();
        }

        return listResult.stream().collect(
                Collectors.toMap(SpecConvertCoefficientDTO::getProductId, p -> p, (v1, v2) -> v1));
    }
}
